'use strict';

const db = uniCloud.database();
const collection = db.collection('food-banner');

exports.main = async (event, context) => {
  const { bannerData } = event.data || {};
  
  if (!bannerData) {
    return {
      code: 400,
      message: '缺少轮播图数据',
      data: null
    };
  }
  
  // 验证必填字段
  if (!bannerData.title || bannerData.title.trim() === '') {
    return {
      code: 400,
      message: '轮播图标题不能为空',
      data: null
    };
  }
  
  if (!bannerData.image) {
    return {
      code: 400,
      message: '轮播图图片不能为空',
      data: null
    };
  }
  
  try {
    // 检查轮播图标题是否已存在
    const existingBanner = await collection.where({
      title: bannerData.title.trim()
    }).get();
    
    if (existingBanner.data.length > 0) {
      return {
        code: 400,
        message: '轮播图标题已存在',
        data: null
      };
    }
    
    // 准备插入数据
    const now = Date.now();
    const insertData = {
      _id: undefined, // 让数据库自动生成
      title: bannerData.title.trim(),
      image: bannerData.image,
      link_type: bannerData.link_type || 0,
      link_value: bannerData.link_value || '',
      sort: bannerData.sort || 0,
      status: bannerData.status !== undefined ? bannerData.status : true,
      create_date: now,
      update_date: now
    };
    
    // 插入数据
    const result = await collection.add(insertData);
    
    return {
      code: 200,
      message: '添加成功',
      data: {
        _id: result.id,
        ...insertData
      }
    };
  } catch (error) {
    console.error('添加轮播图失败:', error);
    return {
      code: 500,
      message: '添加失败',
      data: null
    };
  }
};